package com.nnxy.worktostudy.security.config;

import com.nnxy.worktostudy.security.filter.TokenAuthFilter;
import com.nnxy.worktostudy.security.filter.TokenLoginFilter;
import com.nnxy.worktostudy.security.security.DefaultPasswordEncoder;
import com.nnxy.worktostudy.security.security.TokenManager;
import com.nnxy.worktostudy.security.security.UnauthEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @Author : lu'qz
 * @create 2021/9/22 19:41
 */
@Configuration
public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {
    private TokenManager tokenManager;
    private DefaultPasswordEncoder defaultPasswordEncoder;
    private UserDetailsService userDetailsService;

    @Autowired
    public TokenWebSecurityConfig(TokenManager tokenManager, DefaultPasswordEncoder defaultPasswordEncoder, UserDetailsService userDetailsService) {
        this.tokenManager = tokenManager;
        this.defaultPasswordEncoder = defaultPasswordEncoder;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling()
                .authenticationEntryPoint(new UnauthEntryPoint())
                .and().cors()
                .and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/system/login").permitAll()
                //.anyRequest().authenticated()                //TODO 完善授权系统后打开
                .and().formLogin().loginProcessingUrl("/system/login")
                .and().logout().logoutUrl("/system/logout")
                .and().addFilter(new TokenLoginFilter(tokenManager, authenticationManager()))
                .addFilter(new TokenAuthFilter(authenticationManager(), tokenManager));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(defaultPasswordEncoder);
    }
}
